<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin || empty===true" class="empty">
			<image src="/static/emptyCart.png" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				<text>空空如也</text>
				<view style="margin-top:10px">
					<u-button :ripple="true" type="success" size="mini" @click="navToIndex">去逛逛</u-button>
				</view>
				<!-- <navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">随便逛逛></navigator> -->
			</view>
			<view v-else class="empty-tips">
				<text>空空如也</text>
				<view style="margin-top:10px">
					<u-button :ripple="true" type="success" size="mini" @click="navToLogin">去登录</u-button>
				</view>
				<!-- <view class="navigator" @click="navToLogin">去登录></view> -->
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view style="display: flex;align-items: center;margin: 40rpx;">
				<view style="display: flex;align-items: center;z-index: 9;flex: 1;">
					<u-icon v-if="allChecked" size="60" color="#7EAFA5" name="checkmark-circle-fill"
						@click="check('all')">
					</u-icon>
					<u-icon v-else size="60" color="#888888" style="opacity: 0.1;" name="checkmark-circle"
						@click="check('all')"></u-icon>
					<view>全选</view>
				</view>
				<view style="display: flex;align-items: center;height: 40rpx;">
					<!-- 					<button type="primary" style="background-color:#7EAFA5 ;height: 100%;line-height: 40rpx;"
						size="mini" @click="clearCart">清空</button> -->
					<view class="updateShow" @click="updateClick">
						{{updataStatus?'完成':'编辑'}}
					</view>
					<!-- <view class="clearAll" @click="clearCart">
						清空
					</view> -->
				</view>
			</view>
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="index">
					<view class="store">
						<image class="portrait" :src="item.brandImg" mode="aspectFill"></image>
						&nbsp;&nbsp;&nbsp;{{item.brandName}}
					</view>
					<view class="cart-item">
						<view style="display: flex;align-items: center;justify-content: center;">
							<view style="margin:0 20rpx;">
								<u-icon v-if="item.updateBy" @click="setUpdate(item)" size="50" color="#7EAFA5"
									name="checkmark-circle-fill">
								</u-icon>
								<u-icon v-else @click="setUpdate(item)" size="50" name="checkmark-circle"
									color="#888888" style="opacity: 0.1;">
								</u-icon>
							</view>
							<view style="border-radius: 15rpx;">
								<u-image border-radius="15" width="180rpx" height="180rpx" :src="item.skuDefaultImg"></u-image>
							</view>
						</view>
						<view class="item-right">
							<text class="clamp title">{{item.skuTitle}}</text>
							<view v-if="item.productAttr[0]!=null" style="background-color: #F5F5F5;color: #b3b3b3;">
								【{{item.productAttr[0].key}}】 {{item.productAttr[0].value}}
							</view>
							<view style="position: absolute;bottom: 0;display: flex;right: 20rpx;left: 20rpx;">
								<view style="flex:1;color: #7EAFA5;font-weight: bold;font-size: 38rpx;">
									¥{{(item.price * item.quantity).toFixed(2)}}</view>
								<view style="display: flex;flex: 1;justify-content: center;align-items: center;">
									<!-- <u-number-box :min="1" buttonSize="35" :disabledInput="false"  @change="setShopSize($event,item)"
										:value="item.quantity">
									</u-number-box> -->
									
									<u-number-box :min="1" :value="item.quantity" @change="setShopSize($event,item)"></u-number-box>

									<!-- <view>
										<u-icon @click="setShopSize(item,(item.quantity-1))" size="50" color="#4c4c4c"
											name="minus-circle"></u-icon>
									</view>
									<view style="text-align: center;">
										<input type="number" v-model="item.quantity" @blur="setShopSize(item,item.quantity)" />
									</view>
									<view>
										<u-icon @click="setShopSize(item,(item.quantity+1))" size="50" color="#4c4c4c"
											name="plus-circle"></u-icon>
									</view> -->
								</view>
							</view>
						</view>
						<!-- <text class="del-btn yticon icon-fork" @click="deleteCartItem(index)"></text> -->
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section" v-if="updataStatus">
				<view class="checkbox" style="display: flex;justify-content: center;align-items: center;">
					<view style="display: flex;justify-content: center;align-items: center;z-index: 9;">
						<u-icon v-if="allChecked" size="60" color="#7EAFA5" name="checkmark-circle-fill"
							@click="check('all')">
						</u-icon>
						<u-icon v-else size="60" color="#888888" style="opacity: 0.1;" name="checkmark-circle"
							@click="check('all')"></u-icon>
					</view>
					<!-- <image :src="allChecked?'/static/selected.png':'/static/select.png'" mode="aspectFit" @click="check('all')"></image> -->
				
				</view>
				<view class="addMyLike" @click="addMyLike">
					加入收藏
				</view>
				<view class="deleteOneData" @click="deleteOneData">
					删除
				</view>
			</view>
			<view class="action-section" v-if="!updataStatus">
				<view class="checkbox" style="display: flex;justify-content: center;align-items: center;">
					<view style="display: flex;justify-content: center;align-items: center;z-index: 9;">
						<u-icon v-if="allChecked" size="60" color="#7EAFA5" name="checkmark-circle-fill"
							@click="check('all')">
						</u-icon>
						<u-icon v-else size="60" color="#888888" style="opacity: 0.1;" name="checkmark-circle"
							@click="check('all')"></u-icon>
					</view>
					<!-- <image :src="allChecked?'/static/selected.png':'/static/select.png'" mode="aspectFit" @click="check('all')"></image> -->

				</view>
				<view class="total-box">
					<text class="price">总价格：¥{{total}}</text>
					<!-- 			<text class="coupon">
						已优惠
						<text>0.00</text>
						元
					</text> -->
				</view>
				<button type="primary" :disabled="selectedCartIds" style="background-color:#7EAFA5"
					class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue'
	import { debounce, throttleTime, throttleSetTimeout } from '@/config/throttle.js'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				// 节流控制
				flag: true,
				// total: 0.00, //总价格
				// allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				// selectedCartIds: ''
				// 编辑购物车
				updataStatus: false
			};
		},
		onShow() {
			if (this.hasLogin) {
				this.getShopCart();
				this.updataStatus = false
			}
		},
		watch: {
			//显示空白页
			cartList(e) {
				let empty = e.length === 0 ? true : false;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			},

		},
		computed: {
			...mapState(['hasLogin', 'userInfo']),
			allChecked() {
				let type = true
				this.cartList.forEach(item => {
					if (!item.updateBy) {
						type = false
					}
				})
				return type;
			},
			total() {
				let sum = 0;
				this.cartList.forEach(item => {
					if (item.updateBy) {
						sum += item.price * item.quantity
					}
				})
				return sum;
			},
			selectedCartIds() {
				// this.cartList.forEach(item=>{
				// 	if(item.updateBy){
				// 		return true;
				// 	}
				// })
				if (this.total != 0) {
					return false;
				}
				return true;

			}
		},
		methods: {
			//请求数据
			// async loadData() {
			// 	let list = await this.$api.json('cartList');
			// 	let cartList = list.map(item => {
			// 		item.checked = true;
			// 		return item;
			// 	});
			// 	this.cartList = cartList;
			// 	this.calcTotal(); //计算总价
			// },
			
			
			// 编辑购物车
			updateClick(){
				if(this.updataStatus){
					this.updataStatus = false
				}else {
					this.updataStatus = true
				}
			},
			
			//查询购物车商品
			setUpdate(item) {
				item.updateBy = !item.updateBy
			},
			// 购物数量 节流
			setShopSize(e, item){
				if(this.flag){
					this.flag = false
					console.log(e);
					let num = e.value
					item.quantity = num	
					this.$api.request.setShopSize({
						id: item.id,
						num: num,
					}, res => {
						if(res.code == 200){
							console.log(res);
							// this.getShopCart()
							// item.quantity = num							
						}
						
					})
					setTimeout(() => {						
						this.flag = true						
					},100)
				}
			},
			
			//防抖
			// setShopSize(e, item){
			// 	console.log(e.value);
			// 	const self = this
			// 	clearTimeout(self.times)
				
			// 	self.times = setTimeout(() => {
			// 		let num = e.value
			// 		if (num === 0) {
			// 			// this.$api.msg("")
			// 		} else {
			// 			self.$api.request.setShopSize({
			// 				id: item.id,
			// 				num: num,
			// 			}, res => {
			// 				// console.log(res);
			// 				// this.getShopCart()
			// 				item.quantity = num
			// 			})
			// 		}
			// 	}, 100)
			// },
			getSkuDetail(list) {
				this.cartList = [];
				// this.$api.request.mainSkuList({
				// 	skuId: list.productSkuId
				this.$api.request.skuDetail({
					id: list.productSkuId
				}, res => {
					// list.status=true
					list.productAttr = JSON.parse(list.productAttr);
					// var obj = Object.assign(list, res.data.products[0]);
					var obj = Object.assign(res.data, list);
					this.cartList.push(obj)
				})
			},
			getShopCart() {
				this.cartList = []
				console.log(this.userInfo);

				this.$api.request.getShopCart({}, res => {
					// this.cartList=res.data

					if (res.data.length > 0) {
						uni.setTabBarBadge({
							index: 2,
							text: res.data.length.toString()
						})
					} else {
						uni.removeTabBarBadge({
							index: 2
						})
					}
					// this.cartList = res.data
					res.data.forEach(item => {
						this.getSkuDetail(item)
					})
				})
			},
			inquiryCart() {
				let postData = {
					userUuid: this.userInfo.userUuid
				}
				this.$api.request.cartList(postData, res => {
					if (res.body.status.statusCode === '0') {
						this.cartList = res.body.data.carts;
						this.calcTotal(); //计算总价
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},
			navToIndex() {
				uni.switchTab({
					url: '/pages/sys/home/index'
				})
			},
			navToLogin() {
				uni.navigateTo({
					url: '/pages/sys/common/login'
				})
				// uni.getUserProfile({
				// 	desc: "获取你的昵称、头像、地区及性别",
				// 	success: (res) => {
				// 		console.log(res);
				// 		uni.showLoading({
				// 			//title: '加载中'
				// 		});
				// 		this.$api.request.userLoginOrAdd({
				// 			encryptedData: res.encryptedData,
				// 			iv: res.iv,
				// 			sessionKey: this.session_key,
				// 			wechatId: uni.getStorageSync('openId'),
				// 			sourceType: "APP",
				// 			nickName: res.userInfo.nickName,
				// 			avatarUrl: res.userInfo.avatarUrl
				// 		}, resp => {							
				// 			console.log(resp);
				// 			uni.hideLoading();
				// 			if (resp.code == 200) {
				// 				this.$store.commit("setToken", resp.data.tokenValue)
				// 				this.$store.commit("login", resp.data);
				// 				uni.setStorageSync('authStatus', true)
				// 				this.$api.request.userInfo({},res => {
				// 					if(res.code == 200){
				// 						uni.setStorageSync('userInfo', res.data)
				// 						this.getShopCart();
				// 					}
				// 				})								
								
				// 			}
				// 		})
				// 	}
				// })
			},
			//选中状态处理
			check(type, index) {
				if (type === 'item') {
					this.cartList[index].checked = !this.cartList[index].checked;
				} else {
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item => {
						item.updateBy = checked;
					})
					// this.allChecked = checked;
				}
				// this.calcTotal(type);
			},
			//修改购物车商品数量
			numberChange(data) {
				this.cartList[data.index].unit = data.number;
				this.calcTotal();
				//调用后台修改数量
				let postData = {
					shoppingCartUuid: this.cartList[data.index].shoppingCartUuid,
					unit: data.number
				}
				this.$api.request.setCartNum(postData, res => {
					if (res.body.status.statusCode === '0') {

					} else {
						console.log(res.body.status.errorDesc);
					}
				}, true);
			},
			// 加入收藏
			addMyLike(){
				console.log(this.cartList);
				let respBody = []
				for(let i = 0; i < this.cartList.length; i++){
					if(this.cartList[i].updateBy == true){
						respBody.push(this.cartList[i])
					}
				}
				if(respBody.length > 0){
					uni.showModal({
						content: '添加到我的收藏？',
						success:(e) => {
							// 确定加入收藏
							if(e.confirm) {	
								for (let j = 0; j < respBody.length; j++) {
									this.$api.request.skuCollect({
										price: respBody[j].skuPrice,
										skuId: respBody[j].skuId,
										spuId: respBody[j].spuId,
										spuImage: respBody[j].skuImg,
										spuName: respBody[j].productName
									},res => {
										if(res.message == '取消收藏成功'){
											uni.showToast({
												title: '重复收藏',
												icon: 'none'
											})
										}else{
											uni.showToast({
												title: '收藏成功',
												icon: 'none'
											})
										}
										console.log(res);
									})	
								}			
							}
						}
					})
				}else {
					uni.showToast({
						title: '请选择收藏的商品',
						icon: 'none'
					})
				}
				
			},
			//删除
			deleteCartItem(index) {
				let list = this.cartList;
				let row = list[index];
				let id = row.shoppingCartUuid;
				this.cartList.splice(index, 1);
				this.calcTotal();
				//调用后台移除
				let postData = {
					shoppingCartUuid: id
				}
				this.$api.request.removeCart(postData, res => {
					if (res.body.status.statusCode === '0') {

					} else {
						console.log(res.body.status.errorDesc);
					}
				}, true);
			},
			//删除购物车
			deleteOneData(){
				const that = this
				console.log(this.cartList);
				let respBody = []
				for(let i = 0; i < this.cartList.length; i++){
					if(this.cartList[i].updateBy == true){
						respBody.push(this.cartList[i].id)
					}
				}
				if(respBody.length > 0){
					uni.showModal({
						content: '确定要删除购物车商品吗？',
						success:(e) => {
							// 确定删除
							if(e.confirm) {	
								this.$api.request.deleteOnCart({
									cartItems: respBody
								},res => {
									console.log(res);
									if(res.code == 200){
										// this.getShopCart()
										for(let j = 0; j < this.cartList.length; j++){
											for(let k = 0; k < respBody.length; k++){
												if(this.cartList[j].id == respBody[k]){
													this.cartList.splice(j,1)
												}
											}
										}
										// 获取购物车底部 icon 数量
										this.$api.request.getShopCart({}, res => {
											// this.cartList=res.data
										
											if (res.data.length > 0) {
												uni.setTabBarBadge({
													index: 2,
													text: res.data.length.toString()
												})
											} else {
												uni.removeTabBarBadge({
													index: 2
												})
											}
										})
										// this.updataStatus = false
									}
								})							
							}
						}
					})
				}
				else {
					uni.showToast({
						title: '请选择移出的商品',
						icon: 'none'
					})
				}
				
			},
			//清空
			clearCart() {
				uni.showModal({
					content: '清空购物车？',
					success: (e) => {
						if (e.confirm) {
							this.cartList = [];
							this.$api.request.clearCart({
								memberId: uni.getStorageSync("userInfo").id
							}, res => {
								if (res.code == 200) {
									console.log('购物车商品已清除');
								}
								uni.removeTabBarBadge({
									index: 2
								})
							}, false);
						}
					}
				})
			},
			//计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				let selectedCartIds = '';
				console.log(list);
				list.forEach(item => {
					if (item.checked === true) {
						if (item.productDTO.skuEnabled)
							total += item.productSkuDTO.skuUnitPrice * item.unit;
						else
							total += item.productDTO.unitPrice * item.unit;
						selectedCartIds = selectedCartIds + "," + item.shoppingCartUuid;
					} else if (checked === true) {
						checked = false;
					}
				})
				this.allChecked = checked;
				//商品总额
				this.total = total.toFixed(2);
				//购物车中选择的商品
				if (selectedCartIds.substr(0, 1) == ',') {
					selectedCartIds = selectedCartIds.substr(1);
				}
				this.selectedCartIds = selectedCartIds;
			},
			//创建订单
			createOrder() {
				uni.showModal({
					title: '温馨提示',
					content: '下单请联系店家',
					showCancel: false,
					success:res => {
						if(res.confirm){
							
						}
					}
				})
				return false;
				
				// let ids;
				// this.cartList.forEach(item => {
				// 	if (item.updateBy) {
				// 		if (ids == undefined) {
				// 			ids = item.id
				// 		} else {
				// 			ids += "," + item.id
				// 		}

				// 	}
				// })
				let list = [];
				let spuIdList = []
				console.log(this.cartList);
				this.cartList.forEach(item => {
					if (item.updateBy) {
						list.push(item.productSkuId);
						spuIdList.push(item.spuId)
					}
				})
				uni.setStorageSync("placeOrder", JSON.stringify(list));
				// let sku = {
				//   skuData: this.cartList[0],
				//   buyNum: 1
				// };
				// uni.setStorageSync("placeOrder", JSON.stringify(sku));

				// 商品多了跳转后页面url太长会导致崩溃，改回存id到缓存跳转后请求
				uni.navigateTo({
					url: '/pages/sys/shopCart/placeOrder?spuIdList='+spuIdList.join(",")
				})
			},
			//详情
			navToDetailPage(item) {
				let id = item.productDTO.productUuid;
				uni.navigateTo({
					url: '/pages/product/product?id=' + id
				})
			}
		}
	}
</script>

<style lang='scss'>
	.container {
		padding-bottom: 134upx;

		/* 空白页 */
		.empty {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 100vh;
			padding-bottom: 100upx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			background: #fff;

			image {
				width: 240upx;
				height: 160upx;
				margin-bottom: 30upx;
			}

			.empty-tips {
				font-size: $font-sm+2upx;
				color: #7EAFA5;
			}
		}
	}

	.store {
		display: flex;
		flex-direction: row;
		margin: 40upx 30upx 0 30upx;
		font-size: $font-sm;
		color: $font-color-dark;

		.portrait {
			width: 40upx;
			height: 40upx;
			margin-right: 10upx;
		}
	}

	/* 购物车列表项 */
	.cart-item {
		display: flex;
		position: relative;
		padding: 30upx 40upx;

		.image-wrapper {
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position: relative;

			image {
				border-radius: 8upx;
				width: 100%;
				height: 100%;
			}
		}

		.checkbox {
			position: absolute;
			left: -16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 4upx;
			color: $font-color-disabled;
			background: #fff;
			border-radius: 50px;
		}

		.item-right {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position: relative;
			padding-left: 30upx;

			.title,
			.price {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				height: 40upx;
				line-height: 40upx;
			}

			.attr {
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				height: 50upx;
				line-height: 50upx;
			}

			.price {
				height: 50upx;
				line-height: 50upx;
			}
		}

		.del-btn {
			padding: 4upx 10upx;
			font-size: 34upx;
			height: 50upx;
			color: $font-color-light;
		}
	}

	/* 底部栏 */
	.action-section {
		/* #ifdef H5 */
		margin-bottom: 100upx;
		/* #endif */
		position: fixed;
		left: 30upx;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 690upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;

		.checkbox {
			height: 52upx;
			position: relative;

			image {
				width: 52upx;
				height: 100%;
				position: relative;
				z-index: 5;
			}
		}

		.clear-btn {
			position: absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $font-base;
			color: #fff;
			/* background: $font-color-disabled; */
			background-color: #7EAFA5;
			border-radius: 0 50px 50px 0;
			opacity: 0;
			transition: .2s;

			&.show {
				opacity: 1;
				width: 120upx;
			}
		}

		.total-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			text-align: right;
			padding-right: 40upx;

			.price {
				font-size: $font-lg;
				color: #7EAFA5;
			}

			.coupon {
				font-size: $font-sm;
				color: $font-color-light;

				text {
					color: #7EAFA5
				}
			}
		}

		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px 7EAFA5
		}

		.disabled {
			background-color: #7EAFA5;
			box-shadow: none
		}
	}

	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked {
		color: #7EAFA5
	}
	.clearAll{
		width: 100rpx;
		height: 60rpx;
		border: 1rpx solid red;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.updateShow{
		width: 100rpx;
		height: 60rpx;
		border: 1rpx solid blue;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10rpx;
	}
	.deleteOneData{
		width: 120rpx;
		height: 60rpx;
		border: 1rpx solid red;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 10rpx;
	}
	.addMyLike{
		width: 220rpx;
		height: 60rpx;
		border: 1rpx solid gray;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: auto;
		margin-right: 10rpx;
	}
</style>
